#include<stdio.h>
#include <stdlib.h>
#include<assert.h>
#include<string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>

#define NUM 1024

typedef struct MyFILE
{
    int fd;
    char Buffer[NUM];
    int end;
}MyFILE;

MyFILE* fopen_(const char* pathname, const char* mode)
{
    assert(pathname);
    assert(mode);
    MyFILE* fp = NULL;
    if(strcmp(mode, "r") == 0)
    {}
    else if(strcmp(mode, "r+") == 0)
    {

    }
    else if(strcmp(mode, "w") == 0)
    {
        int fd = open(pathname, O_WRONLY | O_TRUNC | O_CREAT, 0666);
        if(fd >= 0)
        {
            fp = (MyFILE*)malloc(sizeof(MyFILE));
            memset(fp, 0, sizeof(MyFILE));
            fp->fd = fd;
        }
    }
    else if(strcmp(mode, "w+") == 0)
    {

    }
    else if(strcmp(mode, "a") == 0)
    {

    }
    else if(strcmp(mode, "a+") == 0)
    {

    }
    else if(strcmp(mode, "r+") == 0)
    {

    }
    else{
        //什么也不做    
    }

    return fp;

}
void fputs_(const char* message, MyFILE* fp)
{
    assert(message && fp);
    strcpy(fp->Buffer + fp->end, message);
    fp->end += strlen(message);

    //for debug
    //fprintf(stderr,"%s", fp->Buffer);
    printf("fflush:%s\n",fp->Buffer);
    //暂时没有刷i新
    if(fp->fd == 0)
    {
        
    }
    else if(fp->fd == 1)
    {
        if(fp->Buffer[fp->end - 1] == '\n')
        {
     //        fprintf(stderr, "fflush:%s", fp->Buffer);
             write(fp->fd, fp->Buffer, fp->end);
             fp->end = 0;
        }
    }
    else if(fp->fd == 2)
    {

    }
    else{

    }

}
void fflush_(MyFILE* fp)
{
    assert(fp);
    if(fp->end != 0)
    {
        write(fp->fd, fp->Buffer, fp->end);
        syncfs(fp->fd);
        fp->end = 0;
    }
}
void fclose_(MyFILE* fp)
{
    assert(fp);
    fflush_(fp);
    close(fp->fd);
    free(fp);
}
int main()
{
   // close(1);
    MyFILE* fp = fopen_("log.txt", "w");
    if(fp == NULL)
    {
        perror("open file fail");
        return 1;
    }

    fputs_("one:hello 105", fp);
    //fputs_("tow:hello 105", fp);
   // fputs_("therr:hello 105\n", fp);
   // sleep(5);
   // fputs_("fore:hello 105\n", fp);
     fork();
    fclose_(fp);
    return 0;
}
